import json, re
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django_redis import get_redis_connection
from django.views import View

from goods.models import SKU
from users.utils import generate_verify_email_url
from utils.secret import SecretOauth
from .models import User, Address
from django.contrib.auth import login, logout, authenticate
from utils.views import LoginRequiredJSONMixin


class UsernameCountView(View):

    def get(self, requestt, username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据失败'})
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '查询数据出错'})

        return http.JsonResponse({'code': 200, 'errmsg': 'OK', 'count': count})


# 注册视图类
class RegisterView(View):
    def post(self, request):
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        sms_code = json_dict.get('sms_code')

        if not all([username, password, password2, mobile, allow, sms_code]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': '用户名格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '密码格式有误'})

        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入的密码不对'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '电话格式有误'})

        # 从redis 3号库提取短信验证码
        redis_conn = get_redis_connection('verify_code')  # 创建连接到redis的对象
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': '请先勾选用户协议'})

        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile
            )
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})

        login(request, user)
        # return http.JsonResponse({'code':0,'errmsg':'注册成功'})
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})

        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response


# 登录视图类
class LoginView(View):

    def post(self, request):

        # 获取参数
        data_dict = json.loads(request.body.decode())
        username = data_dict.get('username')
        password = data_dict.get('password')
        remembered = data_dict.get('remembered')

        # 校验(整体+单个)
        if not all([username, password]):
            return http.JsonResponse({'code': 400, "errmsg": '缺少必要参数'})

        # 验证是否能够登录
        user = authenticate(request, username=username, password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码不正确'})

        # 状态保持
        login(request, user)

        # 判断是否记住用户
        if remembered != True:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        # 返回json
        # return http.JsonResponse({'code':'0','errmsg':'ok'})

        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response


# 退出登录
class LogoutView(View):

    def delete(self, request):
        # 清理session
        logout(request)
        # 生成响应对象
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 清理cookie
        response.delete_cookie('username')

        return response


# 用户中心类
class UserInfoView(LoginRequiredJSONMixin, View):
    def get(self, request):
        return http.JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }

        })


# 邮箱类
class EmailView(LoginRequiredJSONMixin, View):

    def put(self, request):
        # 获取数据
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        if not re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱格式有误'})

        # 业务处理
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            # logger.error(e)
            return http.JsonResponse({'code': '400', 'errmsg': '添加邮箱失败'})
        # 从celery_tasks中导入
        from celery_tasks.email.tasks import send_verify_email
        # 调用发送的函数
        verify_url = generate_verify_email_url(request)
        send_verify_email.delay(email, verify_url)

        # 响应
        return http.JsonResponse({'code': 0, 'errmsg': '添加邮箱成功'})


# 验证邮箱
class VerifyEmailView(View):

    def put(self, request):
        # 接收token
        token = request.GET.get('token')

        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': 'token缺少'})

        # 解密
        data_dict = SecretOauth().loads(token)

        # 去数据库对比user_id,email
        try:
            user = User.objects.get(pk=data_dict.get('user_id'), email=data_dict.get('email'))
        except Exception as e:
            print(e)
            return http.JsonResponse({'code': 400, 'errmsg': '参数有误'})

        # 修改激活状态
        try:
            user.email_active = True
            user.save()

        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '激活失败'})

        return http.JsonResponse({'code': 0, 'errmsg': '激活成功'})


# 创建收货地址
class CreateAddressView(View):
    '''新增地址'''

    def post(self, request):
        '''实现新增地址逻辑'''

        # 获取地址个数
        count = Address.objects.filter(user=request.user, is_deleted=False).count()

        # 判断是否超过20个
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        #保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

        #设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            return http.JsonResponse({'code':400,'errmsg':'新增地址失效'})

        #新增地址成功,将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

#展示地址
class AddressView(View):

    def get(self,request):

        #获取所有地址

        addresses = Address.objects.filter(user= request.user,is_deleted = False)

        #创建空列表
        address_dict_list = []
        #遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            address_dict_list.append(address_dict)

        #获取默认地址id
        default_id = request.user.default_address_id

        return http.JsonResponse({'code':0,'errmsg':'ok','addresses':address_dict_list,'default_address_id':default_id})


#修改地址
class UpdateDestroyAddressView(View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user = request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
        except Exception as e:
            # logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '更新地址成功',
                                  'address': address_dict})


    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            # logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '删除地址成功'})

#设置默认地址
class DefaultAddressView(View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            # logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置默认地址成功'})

#修改标题
class UpdateTitleAddressView(View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            # logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置地址标题成功'})

#修改密码
class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""

    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
           return http.JsonResponse({'code':400,
                                     'errmsg':'缺少必传参数'})


        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code':400,
                                      'errmsg':'原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code':400,
                                      'errmsg':'密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code':400,
                                      'errmsg':'两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            # logger.error(e)
            return http.JsonResponse({'code':400,
                                      'errmsg':'修改密码失败'})

        # 清理状态保持信息
        logout(request)

        response = http.JsonResponse({'code':0,
                                      'errmsg':'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response

#用户浏览记录,保存,获取
class UserBrowseHistory(View):
    """用户浏览记录"""

    def post(self, request):
        """保存用户浏览记录"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 校验参数:
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku不存在')

        # 保存用户浏览数据
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        save_key = 'history_%s' % request.user.id

        # 先去重: 这里给 0 代表去除所有的 sku_id
        pl.lrem(save_key, 0, sku_id)
        # 再存储
        pl.lpush(save_key, sku_id)
        # 最后截取: 界面有限, 只保留 5 个
        pl.ltrim(save_key, 0, 4)
        # 执行管道
        pl.execute()

        # 响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'OK'})


    def get(self,request):
        '''获取用户浏览记录'''
        #获取redis储存的sku_id列表信息

        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s'% request.user.id,0,-1)

        #根据sku_ids列表数据,查询出商品sku信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id = sku_id)
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'price':sku.price
            })
        return http.JsonResponse({'code':0,'errmsg':'ok','skus':skus})

